//
//  MoviePlayView.m
//  Eyes(StoryBord)
//
//  Created by Jason on 16/3/1.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MoviePlayView.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#import <MediaPlayer/MediaPlayer.h>

// 定义枚举值
typedef NS_ENUM(NSInteger, Movement) {
    HorizontailMovement,
    VerticalMovement
};

@interface MoviePlayView ()
{
    float _nowTime;
    Movement _movement;
}

@property (nonatomic, strong) AVPlayer *player;
@property (weak, nonatomic) IBOutlet UIView *voiceView;
@property (weak, nonatomic) IBOutlet UISlider *voiceSlider;

@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIView *progressView;
@property (weak, nonatomic) IBOutlet UILabel *beginLabel;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@property (strong, nonatomic)NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIView *hiddenView;
@property (assign, nonatomic)float sender;

@property (strong, nonatomic)UISlider *tempSlider;

@end

@implementation MoviePlayView
// 视图初始化方法
- (id)initWithFrame:(CGRect)frame URL:(NSURL *)moviePlayUrl {
    self = [super initWithFrame:frame];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:@"MoviePlayView" owner:nil options:nil] firstObject];
        self.frame = [UIScreen mainScreen].bounds;
        // 设置滑条滑块按钮
        [self.voiceSlider setThumbImage:[UIImage imageNamed:@"nil"] forState:UIControlStateNormal];
        // 改变 view 方向
        self.voiceView.transform = CGAffineTransformMakeRotation(-M_PI_2);
        
        // 根据 url 设置 item  （每次切换视频更换 item 就行）
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:moviePlayUrl];
        // 给播放器添加 item
        self.player = [AVPlayer playerWithPlayerItem:item];
        AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
        layer.frame = frame;
        [self.layer insertSublayer:layer atIndex:0];
        // 必须要写  实现播放的方法
        [_player play];
                
        // 添加轻拍收拾 隐藏控件
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self addGestureRecognizer:tap];
//        // 添加平移手势 快进快退
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [self addGestureRecognizer:pan];
        
        // 隐藏控件
        [self updateDismiss];

        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.6 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
        
        // 系统声音控件
        MPVolumeView *volumView = [[MPVolumeView alloc] initWithFrame:CGRectMake(-100, -100, 0, 0)];
        self.tempSlider = volumView.subviews[0];
        self.voiceSlider.value = self.tempSlider.value;
        [self addSubview:volumView];
        
        
    }
    return self;
}

#pragma mark - 平移手势方法 -
- (void)panAction:(UIPanGestureRecognizer *)pan {
//    return;
    CGPoint point = [pan velocityInView:self];
    switch (pan.state) {
        case UIGestureRecognizerStateBegan: {// 手势开始
            [_timer invalidate];
            // 判断手势横向移动还是竖向移动
            float x = fabs(point.x);
            float y = fabs(point.y);
            if (x > y) {
                _hiddenView.hidden = NO;
                _movement = HorizontailMovement;
                // 获取当前播放进度
                float value = _player.currentTime.value / _player.currentTime.timescale;
                _nowTime = value;
                NSString *style = @">>";
                [self changeProgressLabelWithPlayerValue:value style:style];
            }else {
                _movement = VerticalMovement;
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            // 手势移动
            [self dismiss];
            switch (_movement) {
                case HorizontailMovement: {
                    _nowTime += point.x / _model.duration * 5;
                    if (point.x > 0) {
                        NSString *style = @">>";
                        [self changeProgressLabelWithPlayerValue:_nowTime style:style];
                    }else {
                        NSString *style = @"<<";
                        [self changeProgressLabelWithPlayerValue:_nowTime style:style];
                    }
                    break;
                }
                case VerticalMovement: {
                    [self dismiss];
                    _voiceView.hidden = NO;
                    self.tempSlider.value += -point.y / 10000;
                    self.voiceSlider.value = _tempSlider.value;
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case UIGestureRecognizerStateEnded: {
            // 手势结束
            if (_movement == HorizontailMovement) {
                _hiddenView.hidden = YES;
                [self noDismiss];
                [self updateProgress:_nowTime];
                _progressSlider.value = _nowTime;
                _nowTime = 0;
                [_timer fire];
            }
            break;
        }
        default:
            break;
    }
}
// 改变记录快进快退位置的label
- (void)changeProgressLabelWithPlayerValue:(float)value style:(NSString *)style {
    int newMin = 0;
    int newSec = 0;
    if (value < 0) {
        newMin = 0;
        newSec = 0;
    }else if (value >= _model.duration) {
        newMin = (int)(_model.duration / 60);
        newSec = _model.duration % 60;
    }else {
        newMin = (int)value / 60;
        newSec = (int)value % 60;
    }
    _progressLabel.text = [NSString stringWithFormat:@"%@ %02d:%02d / %02d:%02d", style, newMin, newSec, self.model.duration / 60, self.model.duration % 60];
}
// 定时器方法
- (void)timer:(NSTimer *)timer {
    if (!_progressSlider.highlighted) {
        long long value = self.player.currentTime.value / self.player.currentTime.timescale;
        _beginLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)value / 60, (int)value % 60];
        _progressSlider.value = value;
    }
}

- (void)setModel:(VideoModel *)model {
    _model = model;
    // 赋值 结束label的值以及滑条最大值
    _progressSlider.maximumValue = self.model.duration;
    _endLabel.text = [NSString stringWithFormat:@"%02d:%02d", self.model.duration / 60, self.model.duration % 60];
}

//  播放按钮
- (IBAction)playAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [_player pause];
    }else {
        [_player play];
    }
}
// 返回按钮
- (IBAction)goBack:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(goBack)]) {
        // 关闭定时器
        [_player pause];
        [self.timer invalidate];
        _timer = nil;
        [self.delegate goBack];
    }
}
// 手势方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    _playButton.hidden = !_playButton.hidden;
    _backButton.hidden = !_backButton.hidden;
    _voiceView.hidden = _playButton.hidden;
    _progressView.hidden = !_progressView.hidden;
    [self updateDismiss];
}
// 隐藏控件方法
- (void)dismiss {
    _playButton.hidden = YES;
    _backButton.hidden = YES;
    _voiceView.hidden = YES;
    _progressView.hidden = YES;
}
// 显示控件方法
- (void)noDismiss {
    _playButton.hidden = NO;
    _backButton.hidden = NO;
    _voiceView.hidden = NO;
    _progressView.hidden = NO;
}
// 更新隐藏控件方法
- (void)updateDismiss {
    // 移除上一次的隐藏控件方法
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismiss) object:nil];
    // 添加新的隐藏控件方法
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:5];
}
// 更改滑条当前值
- (IBAction)valueChange:(UISlider *)sender forEvent:(UIEvent *)event {
    [self updateDismiss];
    UITouch *touch = [[event allTouches] anyObject];
    switch (touch.phase) {
        case UITouchPhaseBegan: {
            [_timer invalidate];
            break;
        }
        case UITouchPhaseMoved: {
            // 重新赋值开始 label
            float value = sender.value;
            _beginLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)value / 60, (int)value % 60];
            break;
        }
        case UITouchPhaseEnded: {
            _sender = sender.value;
            [self updateProgress:_sender];
            [_timer fire];
            break;
        }
        default:
            break;
    }
}
// 更新播放进度方法
- (void)updateProgress:(float)value {
    // 获取滑动停止时的进度
    CMTime newTime = _player.currentTime;
    newTime.value = newTime.timescale * value;
    // 更新进度
    [_player seekToTime:newTime];
}


@end












